﻿using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace XieCan.AspMVC.Web.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult UploadFile()
        {
            //最大文件大小
            int maxSize = 1000000;
            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable
            {
                { "image", "gif,jpg,jpeg,png,bmp" },
                { "flash", "swf,flv" },
                { "media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb" },
                { "file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2" }
            };

            var request = HttpContext.Request;
            HttpPostedFileBase imgFile = request.Files["imgFile"];
            if (imgFile == null)
            {
                return ShowResult(1, "请选择文件。");
            }

            //文件保存目录路径
            string uploads = Server.MapPath("/Uploads/");
            if (!Directory.Exists(uploads))
            {
                return ShowResult(1, "上传目录不存在。");
            }

            string dirName = request.QueryString["dir"];
            if (string.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                return ShowResult(1, "目录名不正确。");
            }

            string fileName = imgFile.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return ShowResult(1, "上传文件大小超过限制。");
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return ShowResult(1, "上传文件扩展名是不允许的扩展名。\n只允许" + (string)extTable[dirName] + "格式。");
            }

            //创建文件夹
            uploads += dirName + "/";
            if (!Directory.Exists(uploads))
            {
                Directory.CreateDirectory(uploads);
            }
            uploads += DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo) + "/";
            if (!Directory.Exists(uploads))
            {
                Directory.CreateDirectory(uploads);
            }

            string newFileName = Guid.NewGuid().ToString() + fileExt;
            string filePath = uploads + newFileName;

            imgFile.SaveAs(filePath);

            return ShowResult(0, (uploads + newFileName).Replace(request.PhysicalApplicationPath, "/"));
        }

        private JsonResult ShowResult(int err = 0, string msg = "")
        {
            return err == 0 ? Json(new { error = 0, url = msg }) : Json(new { error = 1, message = msg });
        }
    }
}